<template>
  <div class="bg-white">
    <el-page-header :content="title" @back="back"></el-page-header>
    <el-form ref="form" class="pa-10" :model="form" label-width="120px" style="margin-top: 20px" :rules="rules">
      <el-form-item label="报告名称" prop="reportName">
        <el-input v-model="form.reportName"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="报告类型" prop="reportType">
            <el-select
              v-model="form.reportType"
              :disabled="$route.query.type == 'view'"
              placeholder="请选择报告类型"
              style="width: 100%"
            >
              <el-option v-for="item in reportType" :key="item" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="报告时间设置" prop="reportTime">
            <Expression v-model="form.cronExpression" :disabled="$route.query.type == 'view'"></Expression>

            <!--            <el-col :span='11'>-->
            <!--              <el-select v-model='form.reportFrequency' :disabled="$route.query.type == 'view'" placeholder='请选择'-->
            <!--                         style='width: 100%;'>-->
            <!--                <el-option :label='item.label' :value='item.value' v-for='item in frequentDict' :key='item'></el-option>-->
            <!--              </el-select>-->
            <!--            </el-col>-->
            <!--            <el-col :span='2' style='text-align: center'>-->
            <!--              - -->
            <!--            </el-col>-->
            <!--            <el-col :span='11'>-->
            <!--              <el-time-select-->
            <!--                style='width: 100%;'-->
            <!--                :disabled="$route.query.type == 'view'"-->
            <!--                value-format='HH-mm'-->
            <!--                v-model='form.reportTime'-->
            <!--                :picker-options="{-->
            <!--                    start: '00:00',-->
            <!--                    step: '01:00',-->
            <!--                    end: '24:00'-->
            <!--                  }"-->
            <!--                placeholder='选择时间'>-->
            <!--              </el-time-select>-->
            <!--&lt;!&ndash;              <el-time-picker placeholder='选择时间' :disabled="$route.query.type == 'view'" value-format='HH-mm-ss'&ndash;&gt;-->
            <!--&lt;!&ndash;                              v-model='form.reportTime'&ndash;&gt;-->
            <!--&lt;!&ndash;                              style='width: 100%;'></el-time-picker>&ndash;&gt;-->
            <!--            </el-col>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="通知设置" prop="noticeSetting">
        <el-checkbox-group v-model="noticeSetting" :disabled="$route.query.type == 'view'">
          <el-checkbox label="station" name="noticeSetting">站内</el-checkbox>
          <el-checkbox label="email" name="noticeSetting">邮件</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="报告描述">
        <el-input v-model="form.description" type="textarea" :disabled="$route.query.type == 'view'"></el-input>
      </el-form-item>
      <el-form-item label="报告模板" prop="panelIds">
        <el-cascader
          v-model="form.panelIds"
          filterable
          :disabled="$route.query.type == 'view'"
          placeholder="请选择"
          style="width: 100%"
          :options="templateTree"
          :props="{ checkStrictly: false, label: 'name', value: 'id', emitPath: false }"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="" prop="panelIdsView">
        <div class="chart-panel-box">
          <PanelViewShow ref="panelViewShow" />
        </div>
      </el-form-item>

      <el-row>
        <div>
          <p class="bold">推送用户</p>
          <el-button v-if="$route.query.type !== 'view'" icon="el-icon-plus" size="mini" type="primary" @click="addUser"
            >添加
          </el-button>
          <div class="selectData">
            <el-tag
              v-for="tag in userData"
              :key="tag.id"
              :closable="$route.query.type !== 'view'"
              style="margin-right: 20px; margin-bottom: 10px"
              @close="handleClose(tag, 2)"
            >
              {{ tag.nickName || tag.name }}
            </el-tag>
          </div>
          <p class="bold">推送角色</p>
          <el-button v-if="$route.query.type !== 'view'" icon="el-icon-plus" size="mini" type="primary" @click="addRole"
            >添加
          </el-button>
          <div class="selectData">
            <el-tag
              v-for="tag in roleData"
              :key="tag.id"
              :closable="$route.query.type !== 'view'"
              style="margin-right: 20px; margin-bottom: 10px"
              @close="handleClose(tag, 1)"
            >
              {{ tag.roleName || tag.name }}
            </el-tag>
          </div>
        </div>
      </el-row>

      <el-form-item v-if="$route.query.type == 'view'" label-width="0">
        <el-button size="mini" @click="back">关 闭</el-button>
      </el-form-item>
      <el-form-item v-else label-width="0">
        <el-button size="mini" @click="back">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('form')">保 存</el-button>
      </el-form-item>
    </el-form>
    <userDialog
      v-if="userDialogVisable"
      :dialog-visible="userDialogVisable"
      :user-data="userData"
      @closeUser="closeUser"
    ></userDialog>
    <roleDialog
      v-if="roleDialogVisable"
      :dialog-visible="roleDialogVisable"
      :role-data="roleData"
      @closeRole="closeRole"
    ></roleDialog>
  </div>
</template>

<script>
import { initPanelData, viewPanelLog } from '@/api/panel/panel'
import PanelViewShow from '@/components/vis/panel/list/panel-view-show'
import { groupTree } from '@/api/panel/panel'
import { DAY_TYPE, WEEK_TYPE, MONTH_TYPE, QUARTER_TYPE, YEAR_TYPE } from './dict'
import { requestReportCreate, requestReportUpdate, requestReportDetail } from '@/api/indicator-report'
import userDialog from './dialog/userDialog.vue'
import roleDialog from './dialog/roleDialog.vue'
import Expression from '@/components/expression'
import { personInfo } from '@/api/system/user'

export default {
  name: 'Page',
  components: {
    PanelViewShow,
    userDialog,
    roleDialog,
    Expression,
  },
  props: {},
  data() {
    return {
      roleDialogVisable: false,
      userDialogVisable: false,
      title: '新增报告',
      noticeSetting: [],
      form: {
        description: '',
        reportFrequency: '',
        reportName: '',
        cronExpression: '',
        panelIds: '',
        reportType: '',
        rolePushList: [],
        templateType: 0,
        templateUrl: '',
        userPushList: [],
      },
      rules: {
        reportName: [{ required: true, message: '请输入报告名称', trigger: 'blur' }],
        reportType: [{ required: true, message: '请选择报告类型', trigger: 'change' }],
        panelIds: [{ required: true, message: '请选择报模板', trigger: 'change' }],
        cronExpression: [{ required: true, message: '请选择时间', trigger: 'blur' }],
      },
      roleData: [],
      userData: [],
      templateTree: [],
      reportType: [
        {
          label: '日报',
          value: 'day',
          dictData: DAY_TYPE,
        },
        {
          label: '周报',
          value: 'week',
          dictData: WEEK_TYPE,
        },
        {
          label: '月报',
          value: 'month',
          dictData: MONTH_TYPE,
        },
        {
          label: '季报',
          value: 'quarter',
          dictData: QUARTER_TYPE,
        },
        {
          label: '年报',
          value: 'year',
          dictData: YEAR_TYPE,
        },
      ],
      frequentDict: [],
    }
  },
  watch: {
    'form.reportType': {
      handler(val) {
        this.frequentDict = this.reportType.find((item) => {
          return item.value == val
        })?.dictData
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.getTem()
    this.title = !this.$route.query.id ? '新增报告' : this.$route.query.type == 'edit' ? '编辑报告' : '报告详情'
    this.$route.query.id && this.getDetail(this.$route.query.id)
  },
  methods: {
    nodeClick(data) {
      this.$store.commit('setComponentDataCache', null)
      initPanelData(data.id, false, function (response) {
        viewPanelLog({ panelId: data.id }).then((res) => {})
      })
    },
    getTem() {
      groupTree({}).then((res) => {
        this.templateTree = res.data
      })
    },
    back() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$router.back()
      })
    },
    addUser() {
      this.userDialogVisable = true
    },
    closeUser(val) {
      this.userData = val
      if (val.length) {
        this.form.userPushList = this.userData.map((item) => {
          return item.userId
        })
      } else {
        this.form.userPushList = []
      }
      this.userDialogVisable = false
    },
    addRole() {
      this.roleDialogVisable = true
    },
    closeRole(val) {
      this.roleData = this.roleData.concat(val)
      if (this.roleData.length) {
        this.form.rolePushList = this.roleData.map((item) => {
          return item.roleId
        })
      } else {
        this.form.rolePushList = []
      }
      this.roleDialogVisable = false
    },
    handleClose(tag, type) {
      if (type == 1) {
        this.roleData.splice(this.roleData.indexOf(tag), 1)
        return
      }
      this.userData.splice(this.userData.indexOf(tag), 1)
    },
    getDetail(id) {
      const param = {
        id: id,
      }
      requestReportDetail(param).then((res) => {
        this.nodeClick({ id: res.data.panelIds })
        this.userData = res.data.userPushList
        this.roleData = res.data.rolePushList
        this.form = res.data
        this.form.userPushList = res.data.userPushList.map((item) => {
          return item.userId
        })
        this.form.rolePushList = res.data.rolePushList.map((item) => {
          return item.roleId
        })
        this.noticeSetting = res.data.noticeSetting.split(',')
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.noticeSetting = this.noticeSetting.join(',')
          const api = {
            add: requestReportCreate,
            edit: requestReportUpdate,
          }
          api[this.$route.query.id ? 'edit' : 'add'](this.form).then((res) => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: '操作成功',
              })
              this.back()
            } else {
              this.$message({
                type: 'error',
                message: res.message,
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">
::v-deep .panel-design {
  min-width: 200px;
  min-height: 200px;
}
.chart-panel-box {
  height: 200px;
  width: 300px;
}
::v-deep .panel-design-head {
  display: none;
}
::v-deep .panel-design-preview {
  height: 100%;
}
::v-deep .el-page-header {
  background-color: #ffff;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-page-header__content {
  font-size: 16px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #262626;
}
.bg-white {
  min-height: 100%;
}
.bold {
  font-weight: bolder;
  margin: 20px 0;
}

.selectData {
  margin: 20px;

  .item {
    height: 20px;
    padding: 5px 10px;
    display: flex;
    align-items: center;
    display: inline-block;
  }
}
</style>
